/* Andreas Baum
 * IMClientApp.java
 * Handles the connection of an IM client to the IM server
 * CS 78 - Networks - Programming Assignment 1
 */


package ChatClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;



public class ChatClientApp {

	public static int SERVER_PORT = 4444;

	private static String name;
	private static Socket socket;
	private static PrintWriter out;
	private static BufferedReader in;

	public ChatClientApp() {
		out = null;
		in = null;

	}

	public static void main(String args[]) throws IOException {
		socket = null;
		System.out.println("\t*** Welcome to Andreas Baum's Simple IM Client! ***");

		int userOK = 0;
		String username = null;
		String host = null;
		int hostOK = 0;
		
		while (hostOK == 0) {
			host = "andreas-baum.local";
			hostOK = 1;
			
			if (hostOK==0) {
				host = promptHost();
				hostOK = 1;
			}


			System.out.println("Attempting to connect to " + host + "...");

			try {
				// send connection request:
				socket = new Socket(host, SERVER_PORT);
				// establish in and out streams
				out = new PrintWriter(socket.getOutputStream(), true);
				in = new BufferedReader(new InputStreamReader(
						socket.getInputStream()));
			} catch (UnknownHostException e) {
				// If host can't be found:
				System.err.println("ERROR: Don't know about host: " + host + ".");
				hostOK = 0;
			} catch (IOException e) {
				// If host doesn't accept connections:
				System.err.println("ERROR: Couldn't get I/O for "
						+ "the connection to: " + host + ".");
				hostOK = 0;
			}
		}

		//Confirm connection:
		System.out.println("Connected to " + host 
				+ " on port " + SERVER_PORT + ".");


		while (userOK ==0) {

			if (userOK==0) {
				username = promptUserName();
				userOK = 1;
			}

			System.out.println("Authenticating username...");

			// send username to the server
			out.println("USR " + username);

			// Receive handshake from server (either accepted username
			// or invalid username)
			String response = in.readLine();

			// username is ok
			if (response.toUpperCase().startsWith("PRINT"))
				System.out.println(response.substring(6));

			// username is already used
			else {
				System.out.println(response.substring(4));
				userOK = 0;
			}
		}

		// connection is established, hand it over to a client thread.
		@SuppressWarnings("unused")
		ClientThread clientThread = new ClientThread(socket);

		out.close();
		in.close();

	}

	private static String promptHost() {
		BufferedReader keyboardIn =
			new BufferedReader(
					new InputStreamReader( System.in ) );
		//user enters server host:
		System.out.println("Please enter the address of the host (server):");
		System.out.print("> ");
		String host = null;
		try {
			host = keyboardIn.readLine();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return host;
	}

	private static String promptUserName() {
		BufferedReader keyboardIn =
			new BufferedReader(
					new InputStreamReader( System.in ) );
		String username = "[admin]";
		// user enters username:
		System.out.println("Please enter a username:");
		System.out.print("> ");
		try {
			username = (keyboardIn.readLine()).toLowerCase();
			username = username.trim();
			username = username.split(" ")[0];
			System.out.println("Username set to " + username + ".");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return username;
	}


//	------------------------------------------
//	Standard functions:

//	Returns the name of the client:
	public String getName() {
		return name;
	}

//	Returns the socket:
	public Socket getSocket() {
		return socket;
	}

	// Standard toString method:
	public String toString() {
		return name + "\t" + socket;
	}

}